<template>
  <view class="login">
    <!-- 登录引导 -->
    <view class="login__lead" v-if="!showLoginForm">
      <view class="login__name">
        <image class="login__name-logo" src="/static/common/logo_white.png" />
        <text class="login__name-text">{{ appName }}</text>
      </view>
      <view class="login__name-des">你读过的每一本书都不会被辜负</view>
      <view class="login__buttons">
        <!--  #ifdef  MP-WEIXIN -->
        <button
          lang="zh_CN"
          class="login__buttons-main"
          @click="handleWxappLogin"
        >
          微信授权{{ isRegisted ? '登录' : '注册' }}
        </button>
        <button class="login__buttons-cancel" @click="navigateBack">
          暂不登录
        </button>
        <!--  #endif -->
        <!--  #ifndef  MP-WEIXIN -->
        <button lang="zh_CN" @click="handleWxLogin" class="login__buttons-main">
          微信登录
        </button>
        <view class="login__buttons-inner">
          <button class="login__buttons-sub" @click="handleMobileLogin">
            手机号码登录
          </button>
          <button class="login__buttons-sub" @click="handleRegiste">
            立即注册
          </button>
        </view>
        <!--  #endif -->
      </view>
    </view>
    <transition name="fade">
      <!-- 登录表单 -->
      <view class="login__form" v-if="showLoginForm">
        <view class="login__name dark">
          <image class="login__name-logo" src="/static/common/logo.png" />
          <text class="login__name-text">{{ appName }}</text>
        </view>
        <view class="login__name-des dark">你读过的每一本书都不会被辜负</view>
        <!-- 登录注册切换 -->
        <view class="login__tab">
          <text
            :class="['login__tab-item', { active: currentTab === 'login' }]"
            data-name="login"
            @click="switchTab"
          >
            登录
          </text>
          <text
            :class="['login__tab-item', { active: currentTab === 'registe' }]"
            data-name="registe"
            @click="switchTab"
          >
            注册
          </text>
        </view>
        <view class="login__tab-panel">
          <transition :name="`switch-${switchDirection}`" mode="out-in">
            <view v-if="currentTab === 'login'" class="login__tab-panel-item">
              <!-- 登录 -->
              <LoginForm />
            </view>
          </transition>
          <transition :name="`switch-${switchDirection}`" mode="out-in">
            <view v-if="currentTab === 'registe'" class="login__tab-panel-item">
              <!-- 注册 -->
              <RegisteForm />
            </view>
          </transition>
        </view>
      </view>
    </transition>
  </view>
</template>

<script>
import { mapMutations, mapGetters } from 'vuex';
import { APP_NAME } from '../../config';
import LoginForm from './components/LoginForm';
import RegisteForm from './components/RegisteForm';

export default {
  components: {
    LoginForm,
    RegisteForm,
  },

  data() {
    return {
      showLoginForm: false,
      mobile: '',
      password: '',
      logining: false,
      currentTab: 'login', // 当前显示的tab
      switchDirection: 'right', // 切换动画方向
      isRegisted: false, // 是否已注册
      appName: APP_NAME,
    };
  },

  computed: {
    ...mapGetters(['redirect']),
  },

  created() {
    // #ifdef MP-WEIXIN
    this.isWxappRegisted().then((isRegisted) => {
      this.isRegisted = isRegisted;
    });
    // #endif
  },

  onLoad(option) {
    if (option && option.redirect) {
      this.$store.commit('updateRedirectUrl', {
        type: option.type,
        url: option.redirect,
      });
    }
  },

  methods: {
    ...mapMutations(['login']),

    // 获取微信小程序登录凭证
    getWeappCode() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: function (res) {
            if (res && res.code) {
              resolve(res.code);
            } else {
              const errorMsg = '获取临时凭证失败，错误码: 10100';
              uni.showToast({ title: errorMsg, icon: 'none' });
              reject(new Error(errorMsg));
            }
          },
          error: function (err) {
            const errorMsg = '获取临时凭证失败，错误码: 10200';
            uni.showToast({ title: errorMsg, icon: 'none' });
            reject(new Error(errorMsg));
          },
        });
      });
    },

    // 发送登录请求
    requestLogin(code) {
      return this.$http({
        method: 'POST',
        url: '/api/front/user/login',
        data: {
          wey: 'miniprogram',
          code,
        },
        skipToast: true,
      });
    },

    // 判断微信用户是否已经注册
    isWxappRegisted() {
      return new Promise((resolve) => {
        this.getWeappCode().then((code) => {
          this.$http({
            method: 'POST',
            url: '/api/front/user/is-registe',
            data: {
              wey: 'miniprogram',
              code,
            },
            skipToast: true,
          })
            .then((res) => {
              if (res.ok) {
                resolve(res.registe);
              } else {
                resolve(false);
              }
            })
            .catch(() => {
              resolve(false);
            });
        });
      });
    },

    /**
     * 处理微信小程序登录
     */
    handleWxappLogin() {
      if (this.isRegisted) {
        // 已经注册
        this.getWeappCode().then((code) => {
          this.requestLogin(code)
            .then((res) => {
              if (res && res.ok) {
                // 登录成功
                this.$store.commit('showSuccessTips', '登录成功');
                this.$store.commit('login', {
                  cache: true,
                  token: res.token,
                  userInfo: res.userInfo,
                });
                const {
                  type = 'navigateTo',
                  url = encodeURIComponent('/pages/index/index'),
                } = this.redirect;
                uni[type]({ url: decodeURIComponent(url) });
              } else if (!res.registe) {
                this.isWxappRegisted = false;
              } else {
                // 登录失败
                uni.showToast({
                  title: '登录失败，错误码：10300',
                  icon: 'none',
                });
              }
            })
            .catch((err) => {
              uni.showToast({ title: '登录失败, 错误码：10400', icon: 'none' });
            });
        });
      } else {
        // 尚未注册
        // 获取用户信息
        uni.getUserProfile({
          lang: 'zh',
          desc: '用于完善会员资料',
          success: async (res) => {
            this.handleWeappRegiste({
              username: res.userInfo.nickName,
              avatar: res.userInfo.avatarUrl,
              wey: 'miniprogram',
            });
          },
          fail: (err) => {
            uni.showToast({
              title: '微信授权失败, 错误码：10500',
              icon: 'none',
            });
          },
        });
      }
    },

    // 微信小程序注册
    handleWeappRegiste(params) {
      this.getWeappCode().then((code) => {
        this.$http({
          method: 'POST',
          url: '/api/front/user/registe',
          data: {
            code,
            ...params,
          },
          showLoading: true,
          loadingText: '登录中',
          errorText: '注册用户失败',
        }).then((res) => {
          // 注册成功
          if (res.ok) {
            this.$store.commit('showSuccessTips', '登录成功');
            this.$store.commit('login', {
              cache: true,
              token: res.token,
              userInfo: res.userInfo,
            });
            const {
              type = 'navigateTo',
              url = encodeURIComponent('/pages/index/index'),
            } = this.redirect;
            uni[type]({ url: decodeURIComponent(url) });
          }
        });
      });
    },

    // h5和app微信登录
    handleWxLogin() {},

    // 手机号码登录
    handleMobileLogin() {
      this.showLoginForm = true;
      this.currentTab = 'login';
    },

    handleRegiste() {
      this.showLoginForm = true;
      this.currentTab = 'registe';
    },

    parseAvatar(avatarUrl) {
      return new Promise((resolve) => {
        if (!avatarUrl) {
          resolve('');
          return;
        }
        wx.downloadFile({
          url: avatarUrl,
          success(res) {
            if (res.statusCode === 200) {
              uni.getFileSystemManager().readFile({
                filePath: res.tempFilePath,
                encoding: 'base64',
                success: (readRes) => {
                  if (readRes.data) {
                    const base64 = 'data:image/jpeg;base64,' + readRes.data;
                    resolve(base64);
                  } else {
                    resolve('');
                  }
                },
              });
            } else {
              resolve('');
            }
          },
          fail(err) {
            resolve('');
          },
        });
      });
    },

    // tab切换相关
    switchTab(event) {
      const type = event.mp.currentTarget.dataset.name;
      if (this.currentTab === type) return;
      if (type === 'login') this.switchDirection = 'left';
      if (type === 'registe') this.switchDirection = 'right';
      setTimeout(() => {
        this.currentTab = type;
      }, 200);
    },

    // 返回上一页
    navigateBack() {
      uni.navigateBack();
    },
  },
};
</script>

<style lang='scss'>
page {
  background: #f2f3eb;
}

.login {
  &__lead {
    position: relative;
    min-height: 100vh;
    background: url('https://picture-1256514897.file.myqcloud.com/book/codes/login-bg.png')
      no-repeat;
    background-size: 100% 100%;
    padding-top: 196rpx;
    box-sizing: border-box;
  }

  &__name {
    color: #fff;
    text-align: center;

    &.dark {
      color: $font-color-dark;
    }

    &-logo {
      width: 80rpx;
      height: 80rpx;
      vertical-align: middle;
      margin-top: -4rpx;
    }

    &-text {
      font-size: 40rpx;
    }

    &-des {
      font-size: 14px;
      text-align: center;
      color: #fefefe;

      &.dark {
        color: $font-color-base;
      }
    }
  }

  &__buttons {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 260rpx;

    &-main {
      background: linear-gradient(to right, #2f6bff, #01d0ff);
      border-radius: 0;
      width: 680rpx;
      color: #fff;
      box-shadow: 0 2px 4px #b7e7f3;

      &::after {
        border: none;
      }

      &:active {
        background: linear-gradient(to right, #0e52fa, #03b1d8);
      }
    }

    &-cancel {
      background: #fcfcfc;
      margin-top: 20rpx;
      width: 680rpx;
      color: $font-sub-button;
      border-radius: 0;
      border: none;

      &::after {
        border: none;
      }
    }

    &-inner {
      width: 714rpx;
      margin: 40rpx auto 0;
      display: flex;
      flex-flow: row nowrap;
      justify-content: center;
      align-items: center;
    }

    &-sub {
      width: 320rpx;
      background: #fcfcfc;
      border-radius: 0;
      color: $font-sub-button;

      &::after {
        border: none;
      }

      &:active {
        background: #d7d7d7;
      }
    }
  }

  &__form {
    position: relative;
    min-height: 100vh;
    padding: 198rpx 40rpx 0 40rpx;
    background: #fff;
    box-sizing: border-box;
  }

  &__tab {
    margin-top: 180rpx;
    height: 72rpx;
    margin-left: -10rpx;
    &-item {
      display: inline-block;
      padding: 0 20rpx;
      text-align: center;
      color: $font-color-normal;
      line-height: 72rpx;
      font-size: 38rpx;
      font-weight: 600;
      &.active {
        font-size: 40rpx;
        color: $font-color-title;
        transition: font-size 0.3s;
      }

      &:active {
        color: $font-color-title;
      }

      &:first-child {
        margin-right: 30rpx;
      }
    }

    &-panel {
      width: 100%;
      margin-top: 40rpx;
      position: relative;

      &-item {
        position: absolute;
        width: 100%;
      }
    }
  }
}
</style>
